<template>
  <layout-card :filters="exampleOptions" headline="维修成员管理" @search-change="searchChange" @search-reset="searchReset">
    <template #action>
      <div class="member-action">
        <el-button type="primary" @click="handleDownload">模版下载</el-button>
        <el-upload accept=".xlsx,.xls" :on-change="handleImport" :on-exceed="handleExceed" ref="upload" action="#"
          :limit="1" :auto-upload="false" style="margin:0 0.75rem">
          <!-- <el-button type="primary">Click to upload</el-button> -->
          <el-button type="primary" :loading="btnLoading">导入</el-button>
        </el-upload>
        <el-button type="primary" @click="handleExport">导出</el-button>
        <el-button type="primary" @click="() => openAddDialog()">新增</el-button>
      </div>
    </template>
    <table-common :columns="exampleColumns" :loading="loading" :pagination="pager" :table-data="tableData" size="large"
      @current-change="currentChange" @size-change="sizeChange">
      <template #companyName="{ row }">
        {{ row.companyName || '未分配' }}
      </template>
      <template #memberRoleDesc="{ row }">
          <el-tag hit v-for="item in row.memberRoleDescArr" :key="item" style="margin-right: 5px;">{{ item }}</el-tag>
      </template>
      <template #updateTime="{ row }">
        {{ formatTime(row.updateTime) }}
      </template>
      <template #action="{ row }">
        <el-button class="link-btn" link type="primary" @click="() => openUpdateDialog(row)">编辑</el-button>
        <el-popconfirm title="是否删除?" confirmButtonText="确定" cancelButtonText="取消" @confirm="() => handleDelete(row)">
          <template #reference>
            <el-button class="link-btn" link type="primary">删除</el-button>
          </template>
        </el-popconfirm>
      </template>
    </table-common>
  </layout-card>

  <Edit :visible="centerDialogVisible" :info="info" :companyData="companyData" :roleData="roleData" :userInfo="userInfo"
    @cancel="handleCancel" @ok="handleOk" />
</template>

<script lang="ts" setup>
import dayjs from 'dayjs';
import { ref, reactive, onBeforeMount, computed, toRaw } from 'vue'
import { useStore } from 'vuex'
import LayoutCard from '@/components/LayoutCard/index.vue'
import TableCommon from '@/components/TableCommon/index.vue'
import { exampleColumns } from './config/columns'
import { queryMemberPage, memberDownload, memberImport, memberExport, deleteMember, repCompany } from '@/api/rep/member'
import type { MemberListType, ExportType } from '@/api/rep/member'
import { getResource } from '@/api/resource'
import { image } from '@/assets/index'
import { ElMessage, UploadFile, genFileId } from 'element-plus'
import type { UploadInstance, UploadProps, UploadRawFile } from 'element-plus'
import Edit from './edit.vue'

interface SearchType {
  memberName?: string;
  companyId?: string;
  memberRole?: string;
}

interface RoleDataState {
  memberId: string;
  memberName: string;
  memberPhone: string;
  companyId: string;
  companyName: string;
  companyFullName: string;
  memberRole: string;
  memberRoleDesc: string;
  memberRoleDescArr?: Array<string>,
  remarks: string;
  updateTime: string;
}

interface OptionsType {
  value: string,
  label: string,
  children?: []
}

const formatTime = (str: string) => {
  if (!str) {
    return ''
  }
  return dayjs(str).format('YYYY-MM-DD HH:mm')
}

const store = useStore()
const upload = ref<UploadInstance>()
const centerDialogVisible = ref(false) // 新增/编辑弹窗是否打开
const loading = ref(false)
const btnLoading = ref(false) // 导入按钮加载状态
const tableData = ref<RoleDataState[]>([])
const roleData = ref([]) // 角色列表
const companyData = ref([]) // 维修公司列表
const respOrgId = computed(() => {
  let newInfo = store.state.user.userInfo;
  if (newInfo.organName === 'TOC') {
    return ''
  } else {
    return newInfo.organId
  }
})
const userInfo = computed(() => {
  let newInfo = store.state.user.userInfo;
  return {
    id: newInfo.userId,
    name: newInfo.name,
    organId: newInfo.organId || '',
    organName: newInfo.organName || ''
  }
})
const info = ref(null)
const pager = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

/**
* 打开编辑弹框
*/
const openAddDialog = (row = null) => {
  centerDialogVisible.value = true
  info.value = row
}
/**
* 新增/编辑
*/
const openUpdateDialog = (row = null) => {
  centerDialogVisible.value = true
  info.value = row
}

/**
 * 删除
 */
const handleDelete = async (row: RoleDataState) => {
  const res: any = await deleteMember({
    memberId: `${row.memberId}`, lastMender: userInfo.value
  });
  if (res?.code === '1') {
    if (tableData.value.length === 0) {
      pager.currentPage = 1
    }
    loadData()
    ElMessage.success('已删除！')
  } else {
    ElMessage.error(res?.message || '删除失败，请重试！')
  }
}

/**
* 弹窗点击取消
*/
const handleCancel = () => {
  centerDialogVisible.value = false
}

/**
* 弹窗点击确认
*/
const handleOk = () => {
  centerDialogVisible.value = false
  loadData()
}

// 分页
const sizeChange = (size: number) => {
  pager.pageSize = size
  loadData()
}

const currentChange = (value: number) => {
  pager.currentPage = value
  loadData()
}
// 查询条件
const exampleOptions = ref([
  {
    label: '成员姓名',
    prop: 'memberName',
    type: 'input',
    inputProps: {
      clearable: true,
      placeholder: '请输入'
    }
  },
  {
    label: '人员角色',
    prop: 'memberRole',
    type: 'select',
    defaultValue: '',
    inputProps: {
      options: [
        { label: '全部', value: '' },
      ]
    }
  },
  {
    label: '所属团队',
    prop: 'companyId',
    type: 'cascader',
    defaultValue: [],
    inputProps: {
      options: [
      ]
    }
  },
])
const search = ref<SearchType>({})
const loadData = async () => {
  loading.value = true
  const payload: MemberListType = {
    pageNum: pager.currentPage,
    pageSize: pager.pageSize,
    condition: search.value
  }
  const companyIdLen = payload.condition.companyId?.length || 0;
  if (companyIdLen) {
    payload.condition.companyId = payload.condition.companyId[companyIdLen - 1]
  } else {
    delete payload.condition.companyId
  }
  // TOC可查看所有人员，其他部门的登录用户只可查看责任单位为本部门及未分配的维修成员
  if (respOrgId.value) {
    payload.respOrgId = respOrgId.value
  }
  // ...获取数据
  const res: any = await queryMemberPage(payload);
  loading.value = false
  if (res && res.code === '1') {
    let newData = res?.data?.list;
    newData.forEach((item: RoleDataState) => {
      item.memberRoleDescArr = item.memberRoleDesc && item.memberRoleDesc.split(',') || []
    })
    tableData.value = newData
    pager.total = res?.data?.total
  } else {
    ElMessage.error(res?.message || '获取列表失败，请刷新重试！')
  }
}

const loadCompany = () => {
  let payload = {}
  if (respOrgId.value) {
    payload.respOrgId = respOrgId.value
  }
  repCompany(payload).then(res => {
    if (res?.data?.length) {
      let loop = (data: Array<any>) => {
        let values: any = [];
        data.forEach((item: any) => {
          let newItems: OptionsType = { value: item.companyId, label: item.companyName }
          if (item.children?.length) {
            newItems.children = loop(item.children)
          }
          values.push(newItems)
        })
        return values
      }
      if (res?.data?.length) {
        companyData.value = loop(res.data);
        exampleOptions.value[2].inputProps.options = companyData.value
      }
    }
  })
}

const loadDict = async () => {
  let roleRes = await getResource('rep_member_role'); // 加载角色数据字典
  let newList = roleRes.data?.properties?.meta || []
  roleData.value = newList
  if (newList.length) {
    exampleOptions.value[1].inputProps.options = [{ label: '全部', value: '' }, ...newList];
  }
}

/**
* 点击查询
*/
const searchChange = (data: FilterDataType) => {
  search.value = data
  loadData()
}

/**
* 点击重置
* @param data 数据
*/
const searchReset = (data: FilterDataType) => {
  search.value = data
  pager.currentPage = 1
  pager.pageSize = 10
  loadData()
}

const handleExceed: UploadProps['onExceed'] = (files) => {
  upload.value!.clearFiles()
  const file = files[0] as UploadRawFile
  file.uid = genFileId()
  upload.value!.handleStart(file)
}

/**
 * 导入
 */
const handleImport = (uploadFile: UploadFile) => {
  if (!btnLoading.value) {
    btnLoading.value = true;
    let formData = new FormData()
    formData.append('multipartFile', uploadFile.raw)
    formData.append('name', userInfo.value.name)
    formData.append('organId', userInfo.value.organId)
    formData.append('organName', userInfo.value.organName)
    formData.append('id', userInfo.value.userId)
    memberImport(formData).then((res: any) => {
      if (res?.code === '1') {
        ElMessage.success('导入成功')
        pager.currentPage = 1
        pager.pageSize = 10
        loadData()
      } else {
        ElMessage.error(res?.message || '导入失败')
      }
      btnLoading.value = false
    }).catch((res) => {
      ElMessage.error(res?.message ||'导入失败')
      btnLoading.value = false
    })
  }
}
/**
 * 下载模板
 */
const handleDownload = () => {
  memberDownload().then((res: any) => {
    const link = document.createElement("a");
    const blob = new Blob([res], { type: "application/vnd.ms-excel" });
    link.style.display = "none";
    link.href = URL.createObjectURL(blob);
    link.setAttribute("download", `维修成员模板.xlsx`);  //报表名称可自定义
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  }).catch((res: any) => {
    ElMessage.error(res?.message || '导出失败')
  })
}

/**
 * 导出
 */
const handleExport = () => {
  const payload: ExportType = {
    ...search.value
  }
  const companyIdLen = payload.companyId?.length || 0;
  if (companyIdLen) {
    payload.companyId = payload.companyId[companyIdLen - 1]
  }
  // TOC可查看所有人员，其他部门的登录用户只可查看责任单位为本部门及未分配的维修成员
  if (respOrgId.value) {
    payload.respOrgId = respOrgId.value
  }
  memberExport(payload).then((res: any) => {
    const link = document.createElement("a");
    const blob = new Blob([res], { type: "application/vnd.ms-excel" });
    link.style.display = "none";
    link.href = URL.createObjectURL(blob);
    link.setAttribute("download", `维修成员${dayjs().format('YYYY-MM-DD')}.xlsx`);  //报表名称可自定义
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  }).catch((res: any) => {
    ElMessage.error(res?.message || '导出失败')
  })
}

onBeforeMount(() => {
  loadData();
  loadDict();
  loadCompany();
})

</script>

<style lang="less" scoped>
@import url("./index.less");

.member-action {
  display: flex;

  /deep/.el-upload-list {
    display: none;
  }

}
</style>
